//发送验证码倒计时模块
import 'dart:async';

import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/*
VercodeTimerWidget(
  verifyBuilder: () {
    if (state.phone.length != 11) {
      Toast.showText('请输入正确的手机号');
      return false;
    }
    return true;
  },
  builder: () {
    /// 调取成功接口开始倒计时
    return true;
  },
),
*/

typedef EventBuilder<T> = Future<bool> Function();
typedef VerifyBuilder<T> = bool Function();

class VercodeTimerWidget extends StatefulWidget {
  final EventBuilder builder;
  final VerifyBuilder verifyBuilder;
  // 时间总数
  final int totalTime;

  const VercodeTimerWidget({super.key, this.totalTime = 60, required this.builder, required this.verifyBuilder});
  @override
  State<VercodeTimerWidget> createState() => _VercodeTimerWidgetState();
}

class _VercodeTimerWidgetState extends State<VercodeTimerWidget> {
  Timer? _timer;
  //倒计时数值
  var _countdownTime = 0;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        logs('111_countdownTime=====$_countdownTime');
        if (_countdownTime == 0) {
          bool verify = widget.verifyBuilder.call();
          if (!verify) {
            return;
          }
          FocusScopeNode currentFocus = FocusScope.of(context);
          if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
            FocusManager.instance.primaryFocus!.unfocus();
          }
          bool isStart = await widget.builder.call();
          if (isStart) {
            startCountdown();
          }
        }
      },
      child: Container(
          height: 35.h,
          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.h),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: _countdownTime != 0 ? const Color(0xFF999999) : const Color(0xFF25D4D0),
              borderRadius: BorderRadius.all(Radius.circular(17.r))),
          child: Text(handleCodeAutoSizeText(), style: TextStyle(color: Colors.white, fontSize: 12.sp))),
    );
  }

  String handleCodeAutoSizeText() {
    if (_countdownTime > 0) {
      // return '$_countdownTime' 's后重新发送';
      return '    $_countdownTime' 's    ';
    } else {
      return '获取验证码';
    }
  }

  call(timer) {
    if (_countdownTime < 1) {
      // ignore: avoid_print
      print("定时器取消了");
      _timer!.cancel();
    } else {
      setState(() {
        _countdownTime -= 1;
      });
    }
    logs(_countdownTime);
  }

  //倒计时方法
  startCountdown() {
    //倒计时时间
    _countdownTime = widget.totalTime;
    _stopCountdown();
    if (_timer == null) {
      logs("开启定时器");
      _timer = Timer.periodic(const Duration(seconds: 1), call);
    }
  }

  void _stopCountdown() {
    if (_timer != null) {
      _timer!.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    _stopCountdown();
  }
}
